﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace AuthCenter.Common
{
    public class JwtTools
    {
        public string JwtNewString(IConfiguration _configuration, string uid)
        {
            //2.生成JWT
            //Header,选择签名算法
            var signingAlogorithm = SecurityAlgorithms.HmacSha256;

            //Payload,存放用户信息，下面我们放了一个用户id
            var claims = new[]
            {
         new Claim(type:JwtRegisteredClaimNames.Sub,uid),
         new Claim(type:ClaimTypes.Name,"张三"),
         new Claim(type:ClaimTypes.Email,"zhangsan@123.com"),
         new Claim(type:ClaimTypes.Role,"董事长"),
         new Claim(type:ClaimTypes.DateOfBirth,"2006-05-06",ClaimValueTypes.Date),
         new Claim(type:"CustomClaimType","CustomValue"),
         new Claim(type:"Key","value值"),
            };
            //signature
            //取出私钥并以utf8编码字节输出
            var secretByte = Encoding.UTF8.GetBytes(_configuration["JwtSettings:SecretKey"]);

            //使用非对称算法对私钥进行加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            //使用HmacSha256来验证加密后的私钥生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, signingAlogorithm);

            //生成Token
            var Token = new JwtSecurityToken(
                    issuer: _configuration["JwtSettings:Issuer"],            //发布者
                    audience: _configuration["JwtSettings:Audience"],        //接收者
                    claims: claims,                                          //存放的用户信息
                    notBefore: DateTime.UtcNow,                              //发布时间
                    expires: DateTime.UtcNow.AddDays(1),                     //有效期设置为1天
                    signingCredentials                                       //数字签名

                );


            //生成字符串token
            var TokenStr = new JwtSecurityTokenHandler().WriteToken(Token);
            return TokenStr;
        }
    }
}
